<template>
  <div class="permissions-page">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>权限管理</h1>
        <p>管理系统权限和访问控制</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新增权限
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="权限名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入权限名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="权限分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="全部" value="" />
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权限树形表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>权限列表</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="!selectedPermissions.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button :icon="Download" @click="handleExport">
              导出
            </el-button>
            <el-button :icon="Setting" @click="handleSync">
              同步权限
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="filteredPermissions"
        @selection-change="handleSelectionChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="权限名称" min-width="200">
          <template #default="{ row }">
            <div class="permission-name">
              <el-icon v-if="row.children && row.children.length" class="category-icon">
                <Folder />
              </el-icon>
              <el-icon v-else class="permission-icon">
                <Key />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="权限代码" min-width="150">
          <template #default="{ row }">
            <el-tag v-if="row.code" type="info" size="small">
              {{ row.code }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.category" size="small">
              {{ row.category }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 权限详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="权限详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentPermission" class="permission-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="权限名称">
            {{ currentPermission.name }}
          </el-descriptions-item>
          <el-descriptions-item label="权限代码">
            <el-tag v-if="currentPermission.code" type="info">
              {{ currentPermission.code }}
            </el-tag>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            {{ currentPermission.category || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentPermission.status === 'active' ? 'success' : 'danger'">
              {{ currentPermission.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentPermission.description || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatTime(currentPermission.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentPermission.children && currentPermission.children.length" class="children-section">
          <h3>子权限</h3>
          <el-table :data="currentPermission.children" size="small">
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限代码">
              <template #default="{ row }">
                <el-tag v-if="row.code" type="info" size="small">
                  {{ row.code }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
            <el-table-column label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
                  {{ row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 权限编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      :title="isEdit ? '编辑权限' : '新增权限'"
      width="600px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="editForm.code" placeholder="请输入权限代码，如：user:create" />
        </el-form-item>
        <el-form-item label="上级权限" prop="parent_id">
          <el-tree-select
            v-model="editForm.parent_id"
            :data="permissionTreeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择上级权限（可选）"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="权限分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '保存中...' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限同步对话框 -->
    <el-dialog
      v-model="syncVisible"
      title="权限同步"
      width="500px"
      :before-close="handleCloseSync"
    >
      <div class="sync-content">
        <el-alert
          title="权限同步说明"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>权限同步将从代码中自动扫描并同步权限信息到数据库。</p>
            <p>此操作将：</p>
            <ul>
              <li>添加新发现的权限</li>
              <li>更新已存在权限的信息</li>
              <li>标记已删除的权限为禁用状态</li>
            </ul>
          </template>
        </el-alert>

        <div class="sync-options">
          <el-checkbox v-model="syncOptions.addNew">添加新权限</el-checkbox>
          <el-checkbox v-model="syncOptions.updateExisting">更新已存在权限</el-checkbox>
          <el-checkbox v-model="syncOptions.disableDeleted">禁用已删除权限</el-checkbox>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="syncVisible = false">取消</el-button>
          <el-button type="primary" :loading="syncLoading" @click="handleConfirmSync">
            {{ syncLoading ? '同步中...' : '开始同步' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Delete,
  Download,
  Setting,
  View,
  Edit,
  Folder,
  Key
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const syncLoading = ref(false)
const detailVisible = ref(false)
const editVisible = ref(false)
const syncVisible = ref(false)
const isEdit = ref(false)
const selectedPermissions = ref([])
const currentPermission = ref(null)

const tableRef = ref<any>()
const editFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  name: '',
  code: '',
  parent_id: '',
  category: '',
  description: '',
  status: 'active'
})

// 同步选项
const syncOptions = reactive({
  addNew: true,
  updateExisting: true,
  disableDeleted: false
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 权限分类
const categories = ref([
  '系统管理',
  '用户管理',
  '角色管理',
  '权限管理',
  '内容管理',
  '数据管理',
  '系统设置'
])

// 权限列表
const permissions = ref([
  {
    id: 1,
    name: '系统管理',
    code: '',
    description: '系统管理相关权限',
    category: '系统管理',
    status: 'active',
    created_at: '2024-01-01 00:00:00',
    children: [
      {
        id: 2,
        name: '用户管理',
        code: 'system:user',
        description: '用户管理权限',
        category: '系统管理',
        status: 'active',
        created_at: '2024-01-01 00:00:00',
        children: [
          {
            id: 3,
            name: '查看用户',
            code: 'system:user:view',
            description: '查看用户列表',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          },
          {
            id: 4,
            name: '创建用户',
            code: 'system:user:create',
            description: '创建新用户',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          },
          {
            id: 5,
            name: '编辑用户',
            code: 'system:user:edit',
            description: '编辑用户信息',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          },
          {
            id: 6,
            name: '删除用户',
            code: 'system:user:delete',
            description: '删除用户',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          }
        ]
      },
      {
        id: 7,
        name: '角色管理',
        code: 'system:role',
        description: '角色管理权限',
        category: '系统管理',
        status: 'active',
        created_at: '2024-01-01 00:00:00',
        children: [
          {
            id: 8,
            name: '查看角色',
            code: 'system:role:view',
            description: '查看角色列表',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          },
          {
            id: 9,
            name: '创建角色',
            code: 'system:role:create',
            description: '创建新角色',
            category: '系统管理',
            status: 'active',
            created_at: '2024-01-01 00:00:00'
          }
        ]
      }
    ]
  },
  {
    id: 10,
    name: '内容管理',
    code: '',
    description: '内容管理相关权限',
    category: '内容管理',
    status: 'active',
    created_at: '2024-01-01 00:00:00',
    children: [
      {
        id: 11,
        name: '文章管理',
        code: 'content:article',
        description: '文章管理权限',
        category: '内容管理',
        status: 'active',
        created_at: '2024-01-01 00:00:00'
      }
    ]
  }
])

// 权限树选项（用于选择上级权限）
const permissionTreeOptions = computed(() => {
  const buildTree = (items: any[], excludeId?: string | number) => {
    return items
      .filter(item => item.id !== excludeId)
      .map(item => ({
        id: item.id,
        name: item.name,
        children: item.children ? buildTree(item.children, excludeId) : []
      }))
  }
  return buildTree(permissions.value, editForm.id)
})

// 过滤后的权限列表
const filteredPermissions = computed(() => {
  let result = permissions.value

  if (searchForm.name) {
    const filterByName = (items: any[]): any[] => {
      const filtered: any[] = []
      items.forEach(item => {
        const nameMatch = item.name.toLowerCase().includes(searchForm.name.toLowerCase())
        const childrenMatch = item.children ? filterByName(item.children) : []
        
        if (nameMatch || childrenMatch.length > 0) {
          filtered.push({
            ...item,
            children: childrenMatch.length > 0 ? childrenMatch : item.children
          })
        }
      })
      return filtered
    }
    result = filterByName(result)
  }

  if (searchForm.category) {
    const filterByCategory = (items: any[]): any[] => {
      const filtered: any[] = []
      items.forEach(item => {
        const categoryMatch = item.category === searchForm.category
        const childrenMatch = item.children ? filterByCategory(item.children) : []
        
        if (categoryMatch || childrenMatch.length > 0) {
          filtered.push({
            ...item,
            children: childrenMatch.length > 0 ? childrenMatch : item.children
          })
        }
      })
      return filtered
    }
    result = filterByCategory(result)
  }

  if (searchForm.status) {
    const filterByStatus = (items: any[]): any[] => {
      const filtered: any[] = []
      items.forEach(item => {
        const statusMatch = item.status === searchForm.status
        const childrenMatch = item.children ? filterByStatus(item.children) : []
        
        if (statusMatch || childrenMatch.length > 0) {
          filtered.push({
            ...item,
            children: childrenMatch.length > 0 ? childrenMatch : item.children
          })
        }
      })
      return filtered
    }
    result = filterByStatus(result)
  }

  return result
})

// 表单验证规则
const editRules: FormRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9:_-]*$/, message: '权限代码格式不正确', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择权限分类', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 方法
const handleSearch = () => {
  pagination.page = 1
  // 树形表格不需要重新加载数据，直接通过计算属性过滤
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    status: ''
  })
}

const handleCreate = () => {
  isEdit.value = false
  editVisible.value = true
  resetEditForm()
}

const handleView = (row: any) => {
  currentPermission.value = row
  detailVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  editVisible.value = true
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    parent_id: row.parent_id || '',
    category: row.category,
    description: row.description,
    status: row.status
  })
}

const handleDelete = async (row: any) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该权限下还有子权限，请先删除子权限')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用删除API
    ElMessage.success('删除成功')
    loadPermissions()
  } catch {
    // 用户取消删除
  }
}

const handleBatchDelete = async () => {
  if (!selectedPermissions.value.length) {
    ElMessage.warning('请选择要删除的权限')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPermissions.value.length} 个权限吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用批量删除API
    ElMessage.success('批量删除成功')
    selectedPermissions.value = []
    loadPermissions()
  } catch {
    // 用户取消删除
  }
}

const handleStatusChange = async (row: any) => {
  try {
    // 这里调用状态更新API
    ElMessage.success(`权限状态已${row.status === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.error('状态更新失败')
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleSync = () => {
  syncVisible.value = true
}

const handleSelectionChange = (selection: any[]) => {
  selectedPermissions.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadPermissions()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadPermissions()
}

const handleSubmit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 这里调用保存API
        await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
        
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        editVisible.value = false
        loadPermissions()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleConfirmSync = async () => {
  syncLoading.value = true
  try {
    // 这里调用权限同步API
    await new Promise(resolve => setTimeout(resolve, 2000)) // 模拟API调用
    
    ElMessage.success('权限同步成功')
    syncVisible.value = false
    loadPermissions()
  } catch (error) {
    ElMessage.error('权限同步失败')
  } finally {
    syncLoading.value = false
  }
}

const handleCloseDetail = () => {
  detailVisible.value = false
  currentPermission.value = null
}

const handleCloseEdit = () => {
  editFormRef.value?.resetFields()
  editVisible.value = false
  resetEditForm()
}

const handleCloseSync = () => {
  syncVisible.value = false
  Object.assign(syncOptions, {
    addNew: true,
    updateExisting: true,
    disableDeleted: false
  })
}

const resetEditForm = () => {
  Object.assign(editForm, {
    id: '',
    name: '',
    code: '',
    parent_id: '',
    category: '',
    description: '',
    status: 'active'
  })
}

const loadPermissions = async () => {
  loading.value = true
  try {
    // 这里调用权限列表API
    await new Promise(resolve => setTimeout(resolve, 500)) // 模拟API调用
    
    // 计算总数（包括子权限）
    const countPermissions = (items: any[]): number => {
      let count = 0
      items.forEach(item => {
        count++
        if (item.children) {
          count += countPermissions(item.children)
        }
      })
      return count
    }
    pagination.total = countPermissions(permissions.value)
  } catch (error) {
    ElMessage.error('加载权限列表失败')
  } finally {
    loading.value = false
  }
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(() => {
  loadPermissions()
})
</script>

<style scoped>
.permissions-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-icon {
  color: #409eff;
}

.permission-icon {
  color: #67c23a;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.permission-detail {
  padding: 20px 0;
}

.children-section {
  margin-top: 30px;
}

.children-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.sync-content {
  padding: 10px 0;
}

.sync-options {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .permissions-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
}
</style>